package com.wms.handler;

import com.wms.entity.WmsReturnMaterial;
import org.apache.log4j.Logger;
import org.codehaus.jettison.json.JSONException;
import org.codehaus.jettison.json.JSONObject;
import org.openbravo.client.kernel.BaseActionHandler;
import org.openbravo.dal.core.OBContext;
import org.openbravo.dal.service.OBDal;
import org.openbravo.erpCommon.utility.OBMessageUtils;
import java.util.Map;

/**
 * 车间退料打印
 * @author zt
 */
public class ReturnMaterialPrintHandler extends BaseActionHandler {
	private Logger logger = Logger.getLogger(this.getClass());
	@Override
	protected JSONObject execute(Map<String, Object> parameters, String data) {
		JSONObject jsonRep = new JSONObject();
		try {
			OBContext.setAdminMode();
			
			JSONObject jsonData = new JSONObject(data);
			String recordId = jsonData.getString("recordId");
			
			WmsReturnMaterial rMaterial = OBDal.getInstance().get(WmsReturnMaterial.class, recordId);

			JSONObject message = new JSONObject();
			if (rMaterial.getWmsReturnMaterialMxList().isEmpty()) {
				message.put("severity", "error");
				message.put("text", OBMessageUtils.messageBD("请先导入退料清单！"));
				return jsonRep;
			} else {
				if ("CREATE".equals(rMaterial.getStatus())) {
					rMaterial.setStatus("PRINT");//设置状态为已打印
					OBDal.getInstance().save(rMaterial);
				}
				message.put("severity", "success");
				message.put("text", OBMessageUtils.messageBD("修改车间退料状态成功！"));
				message.put("dataId", recordId);
			}
	        jsonRep.put("message", message);
	        OBDal.getInstance().commitAndClose();
		} catch (Exception e) {
	        OBDal.getInstance().rollbackAndClose();
			logger.error("修改车间退料状态异常：" + e.getMessage(), e);
			e.printStackTrace();
			try {
		        JSONObject errorMessage = new JSONObject();
		        errorMessage.put("severity", "error");
		        errorMessage.put("text", OBMessageUtils.messageBD("修改车间退料状态异常！<br/>" + e.getMessage()));

		        jsonRep.put("message", errorMessage);
		        jsonRep.put("retryExecution", true);
			} catch (JSONException e1) {
			}
		}finally{
			 OBContext.restorePreviousMode();
		}
		return jsonRep;
	}
}
